package com.ict.web.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ict.common.core.domain.entity.SysDept;
import com.ict.common.utils.SecurityUtils;
import com.ict.common.utils.StringUtils;
import com.ict.system.mapper.SysUserRoleMapper;
import com.ict.system.service.ISysDeptService;
import com.ict.system.service.ISysRoleService;
import com.ict.web.constant.Constants;
import com.ict.web.constant.ProjectStatusEnum;
import com.ict.web.controller.file.domain.YzqFile;
import com.ict.web.controller.file.mapper.YzqFileMapper;
import com.ict.web.controller.file.service.IYzqFileService;
import com.ict.web.domain.AnnualProjectPlan;
import com.ict.web.domain.ExtractExpert;
import com.ict.web.domain.OrganizationManagement;
import com.ict.web.dto.QueryNoticeDto;
import com.ict.web.mapper.HomePageTotalMapper;
import com.ict.web.msg.domain.SysMsg;
import com.ict.web.msg.dto.QuerySysMsgDto;
import com.ict.web.msg.service.ISysMsgService;
import com.ict.web.msg.vo.SysMsgVo;
import com.ict.web.service.HomePageTotalService;
import com.ict.web.service.IAnnualProjectPlanService;
import com.ict.web.service.INoticeService;
import com.ict.web.service.IOrganizationManagementService;
import com.ict.web.utils.pdf.RoleUtil;
import com.ict.web.vo.NoticeAndMsgVo;
import com.ict.web.vo.NoticeVo;
import com.ict.web.vo.ResourceApplyAndCollectVo;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.security.Security;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class HomePageTotalServiceImpl implements HomePageTotalService {

    @Resource
    private HomePageTotalMapper homePageTotalMapper;
    @Autowired
    private ISysDeptService deptService;
    @Resource
    private INoticeService noticeService;
    @Autowired
    private ISysMsgService msgService;
    @Autowired
    private IOrganizationManagementService organizationManagementService;
    @Autowired
    private IYzqFileService fileService;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private IAnnualProjectPlanService annualProjectPlanService;

    @Override
    public Map<String,String> homePageStatistics() {
        HashMap<String, String> map = new HashMap<>();
        Long deptId = SecurityUtils.getDeptId();
        String deptName=deptService.selectDeptById(deptId).getDeptName();
        Long userId = SecurityUtils.getUserId();
        if(RoleUtil.getUserRole(Constants.ROLE_TYPE_BIGDATA)||RoleUtil.getUserRole(Constants.ROLE_TYPE_BIGDATA_NORMAL)){
            deptName=null;
            userId=null;
        }

        map.put("applicationNum",homePageTotalMapper.applicationNum(deptName,userId).getTotalNumber());//正在申报数量
        map.put("implementNum",homePageTotalMapper.implementNum(deptName,userId).getTotalNumber());//正在实施数量
        map.put("preliminaryInspectionNum",homePageTotalMapper.preliminaryInspectionNum(deptName,userId).getTotalNumber());//验收备案数量
        map.put("constructionNum",homePageTotalMapper.constructionNum(Arrays.asList("0","1"),deptName,userId).getTotalNumber());//建设类项目数量
        map.put("buyAndServiceNum",homePageTotalMapper.constructionNum(Arrays.asList("2"),deptName,userId).getTotalNumber());//购买服务类数量
        map.put("operationAndMaintenanceNum",homePageTotalMapper.constructionNum(Arrays.asList("3"),deptName,userId).getTotalNumber());//运维类项目数量
        map.put("applicationReckon",homePageTotalMapper.applicationNum(deptName,userId).getTotalEstimation().replaceAll("[.](.*)",""));//正在申报估算
        map.put("implementReckon",homePageTotalMapper.implementNum(deptName,userId).getTotalEstimation().replaceAll("[.](.*)",""));//正在实施估算
        map.put("preliminaryInspectionReckon",homePageTotalMapper.preliminaryInspectionNum(deptName,userId).getTotalEstimation().replaceAll("[.](.*)",""));//验收备案估算
        map.put("constructionReckon",homePageTotalMapper.constructionNum(Arrays.asList("0","1"),deptName,userId).getTotalEstimation().replaceAll("[.](.*)",""));//建设类项目估算
        map.put("buyAndServiceReckon",homePageTotalMapper.constructionNum(Arrays.asList("2"),deptName,userId).getTotalEstimation().replaceAll("[.](.*)",""));//购买服务类估算
        map.put("operationAndMaintenanceReckon",homePageTotalMapper.constructionNum(Arrays.asList("3"),deptName,userId).getTotalEstimation().replaceAll("[.](.*)",""));//运维类项目估算
        return map;

    }

    @Override
    public List<ResourceApplyAndCollectVo> resourceApplyAndCollect() {

        List<ResourceApplyAndCollectVo> resourceApplyAndCollectVos = new ArrayList<>();

        List<Long> userIds = sysUserRoleMapper.getUserIdByRoleId(Constants.ROLE_TYPE_PROJECT);
        if (userIds.contains(SecurityUtils.getUserId())) {
            LambdaQueryWrapper<AnnualProjectPlan> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AnnualProjectPlan::getIsState,ProjectStatusEnum.ANNUAL_PROJECT_PLAN_REPORTING.get().getStatus())
                    .eq(AnnualProjectPlan::getIsDelete, Constants.DELETE_STATUS_NORMAL);
            AnnualProjectPlan annualProjectPlan = annualProjectPlanService.getOne(lambdaQueryWrapper);
            ResourceApplyAndCollectVo resourceApplyAndCollectVo = new ResourceApplyAndCollectVo();

            if (StringUtils.isNotNull(annualProjectPlan)) {
                resourceApplyAndCollectVo.setName(annualProjectPlan.getName());
                resourceApplyAndCollectVo.setNode("年度计划");
                resourceApplyAndCollectVo.setUpdateTime(annualProjectPlan.getEndTime());
                resourceApplyAndCollectVo.setPlanId(annualProjectPlan.getPlanId());
                resourceApplyAndCollectVos.add(resourceApplyAndCollectVo);
            }
        }

        Long deptId = SecurityUtils.getDeptId();
        String deptName=deptService.selectDeptById(deptId).getDeptName();
        if(RoleUtil.getUserRole(Constants.ROLE_TYPE_BIGDATA)||RoleUtil.getUserRole(Constants.ROLE_TYPE_BIGDATA_NORMAL)){
            deptName=null;
        }
        List<ResourceApplyAndCollectVo> resourceApplyAndCollectVos1 = homePageTotalMapper.resourceApplyAndCollectNum(deptName);
        resourceApplyAndCollectVos1.stream().forEach(s->{
            s.setNodeName(ProjectStatusEnum.getEnum(s.getState()).getNode());
        });
        //大数据局待办事项：排除转三方项目状态为安排评审会议、意见汇总、现场论证
        for (int i = 0; i <resourceApplyAndCollectVos1.size() ; i++) {
            ResourceApplyAndCollectVo vo = resourceApplyAndCollectVos1.get(i);
            if(StringUtils.isNotNull(vo.getTripartiteId())){
                if(ProjectStatusEnum.ARRANGE_REVIEW_MEETING_TO_BE_EXTRACTED.get().getStatus().equals(vo.getState())
                        ||ProjectStatusEnum.COMMENTS_SUMMARY_TO_BE_APPROVED.get().getStatus().equals(vo.getState())
                        ||ProjectStatusEnum.ONLINE_PREQUALIFICATION_PENDING_ARRANGE.get().getStatus().equals(vo.getState())
                        ||ProjectStatusEnum.SCHEME_DECLARATION_UPDATE_TO_BE_APPROVED.get().getStatus().equals(vo.getState())
                        ||ProjectStatusEnum.ON_SITE_DEMONSTRATION_TO_BE_REVIEWED.get().getStatus().equals(vo.getState())){
                    resourceApplyAndCollectVos1.remove(vo);
                }
            }
        }
        resourceApplyAndCollectVos.addAll(resourceApplyAndCollectVos1);

        return resourceApplyAndCollectVos;
    }

    @Override
    public List<SysMsgVo> msgList(String msgName) {
        List<NoticeAndMsgVo> list = new ArrayList<>();
        QuerySysMsgDto querySysMsgDto = new QuerySysMsgDto();
        querySysMsgDto.setReceiveUserId(SecurityUtils.getUserId());
        if (StringUtils.isNotEmpty(msgName)) {
            querySysMsgDto.setTitle(msgName);
        }
        List<SysMsgVo> sysMsgVos = msgService.selectSysMsgList(querySysMsgDto);
        sysMsgVos.forEach(s->{
            s.setCreateTime(s.getCreateTime());
            s.setNoticeTitle(s.getTitle());
            s.setNoticeContent(s.getContent());
            YzqFile yzqFile = fileService.getById(s.getNoticeFileId());
            if (StringUtils.isNotNull(yzqFile)){
                s.setNoticeFileName(yzqFile.getFileName());
                s.setNoticeFileUrl(yzqFile.getFileUrl());
            }
            if (StringUtils.isNotNull(s.getNoticeId())) {
                s.setNoticeType(NoticeAndMsgVo.NOTICE_TYPE_NOTICE);
            }else {
                s.setNoticeType(NoticeAndMsgVo.NOTICE_TYPE_MSG);
            }

            if (StringUtils.isNotNull(s.getPlanId())) {
                s.setNoticeType(NoticeAndMsgVo.NOTICE_TYPE_ANNUAL_PLAN);
            }
        });
//        if(StringUtils.isNotEmpty(msgName)){
//            List<NoticeAndMsgVo>  filterInfo= list .stream().filter(orderInfo-> Boolean.FALSE?orderInfo.getNoticeTitle().equals(msgName):
//                    orderInfo.getNoticeTitle().contains(msgName))
//                    .sorted(Comparator.comparing(NoticeAndMsgVo::getCreateTime).reversed())
//                    .collect(Collectors.toList());
//            return filterInfo;
//        }

        return sysMsgVos;
    }

    @Override
    public int countByUserId(Long userId) {
        return msgService.countByUserId(SecurityUtils.getUserId());
    }

    /**
     * 根据通知id修改通知状态为已读
     *
     * @param id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReadFlagById(String id) {
        LambdaQueryWrapper<SysMsg> wrapper = Wrappers.<SysMsg>lambdaQuery()
                .eq(SysMsg::getId, id)
                .eq(SysMsg::getMsgStatus, SysMsg.STATUS_NORMAL)
                .eq(SysMsg::getReadFlag, SysMsg.READ_FLAG_NORMAL);
        SysMsg sysMsg = msgService.getOne(wrapper);
        if (!StringUtils.isNotNull(sysMsg)) {
            LambdaQueryWrapper<SysMsg> wrapper1 = Wrappers.<SysMsg>lambdaQuery()
                    .eq(SysMsg::getId, id)
                    .eq(SysMsg::getMsgStatus, SysMsg.STATUS_UNNORMAL)
                    .eq(SysMsg::getReadFlag, SysMsg.READ_FLAG_NORMAL);
            SysMsg sysMsg1 = msgService.getOne(wrapper1);
            if (StringUtils.isNotNull(sysMsg1.getPlanId())) {
                sysMsg = sysMsg1;
            }
        }
        Assert.isTrue(sysMsg!=null,"数据不存在！");
        sysMsg.setReadFlag(SysMsg.READ_FLAG_UNNORMAL);
        Long userId = SecurityUtils.getUserId();
        sysMsg.setUpdateBy(String.valueOf(userId));
        sysMsg.setUpdateTime(LocalDateTime.now());
        return msgService.updateById(sysMsg);
    }


}
